package CtrLayer;

import java.util.ArrayList;

import DBLayer.*;
import ModelLayer.*;



public class SalesOrderCtr
{
    // instance variables - replace the example below with your own
    private CustomerCtr customerCtr;
    private ProductCtr productCtr;
	private SalesOrder salesOrder;
    private DBSalesOrder salesOrderDB;
    
    private static SalesOrderCtr instance;
    
	private SalesOrderCtr() {
		salesOrderDB = new DBSalesOrder();
	}
	
	public static SalesOrderCtr getInstance() {
        if (instance == null) {
            instance = new SalesOrderCtr();
        }
        return instance;
    }

	public void createSalesOrder() {
		salesOrder = new SalesOrder();
	}

	public Customer findCustomer(int phoneNo)
	{
		return customerCtr.getCustomerByPhoneNo(phoneNo);	
	}

    public void addCustomer(Customer c)
    {
        
    	salesOrder.setC(c);
    }
    
    public void createPartOrder(Product p, int amount)
    {
    	
        PartOrder po = new PartOrder(p, amount, p.getSalesPrice() * amount);
        salesOrder.getPo().add(po);
    }
    public void updatePartOrder(PartOrder po, int amount)
    {
    	int index = salesOrder.getPo().indexOf(po);
    	po.setAmount(amount);
    	salesOrder.getPo().set(index, po);
    }
    
    public void removePartOrder(PartOrder po)
    {
    	salesOrder.getPo().remove(po);
    }
    
    public ArrayList<PartOrder> listPartOrders()
    {
    	return salesOrder.getPo();
    }
   
    /**
     * adds a order to the library
     */
    public void insertSalesOrder(SalesOrder so) throws Exception
    {
    	salesOrderDB.insertSalesOrder(so);
    }
    
    public SalesOrder getSalesOrder() {
		return salesOrder;
	}

	public void setSalesOrder(SalesOrder salesOrder) {
		this.salesOrder = salesOrder;
	}

	public ArrayList<SalesOrder> listSalesOrders() {
		DBSalesOrder dbSO = new DBSalesOrder();
		return dbSO.getAllSalesOrder();
	}
	
	public ArrayList<SalesOrder> listSalesOrders(String filter) {
		DBSalesOrder dbSO = new DBSalesOrder();
		return dbSO.getAllSalesOrder(filter);
	}

	public void removeSalesOrder(int salesOrderId) {
		DBSalesOrder dbSO = new DBSalesOrder();
		SalesOrder SalesOrderObj = dbSO.searchSalesOrder(salesOrderId);
		
		try{
			DBConnection.startTransaction();
			dbSO.deleteSalesOrder(SalesOrderObj);
			DBConnection.commitTransaction();
		}
		catch(Exception e)
		{
			DBConnection.rollbackTransaction();
		}
	}
}
